package com.lbj.googleplay.googleplay100.ui.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.lbj.googleplay.googleplay100.R;
import com.lbj.googleplay.googleplay100.ui.fragment.BaseFragment;
import com.lbj.googleplay.googleplay100.ui.fragment.FragmentFactory;
import com.lbj.googleplay.googleplay100.ui.view.PagerTab;
import com.lbj.googleplay.googleplay100.utils.UIUtils;

//主页面
public class BaseActivity extends AppCompatActivity {

    private PagerTab mPagerTab;
    private ViewPager mViewPager;
    private MyAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPagerTab = findViewById(R.id.pager_tab);
        mViewPager = findViewById(R.id.viewpager);
        mAdapter = new MyAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mPagerTab.setViewPager(mViewPager);
        //添加页面切换时的监听
        mPagerTab.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                BaseFragment fragment = FragmentFactory.createFragment(position);
                //加载数据
                fragment.loadData();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    class MyAdapter extends FragmentPagerAdapter{

        private String[] tabNames;//页签标题数组

        public  MyAdapter(FragmentManager manager){
            super(manager);
            tabNames  = UIUtils.getStringArray(R.array.tab_names);

        }
        //返回当前fragment对应的标题
        @Override
        public CharSequence getPageTitle(int position) {

            return tabNames[position];
        }

        //返回fragment的数量
        @Override
        public int getCount() {
            return tabNames.length;
        }
        //返回当前页面位置的fragment对象
        @Override
        public Fragment getItem(int position) {

            Fragment fragment = FragmentFactory.createFragment(position);

            return fragment;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}
